// component/share/share.js
const app = getApp()

import ajax from '../../utils/index'
Component({
    /**
     * 组件的属性列表
     */
    properties: {
        type:{ //1.营销活动,2.园区首页id, 3企业首页id
            type:String,
            value: 1,
        },
        gardenId:{
            type:String,
            value: '',
        },
        enterpriseId:{
            type:String,
            value: '',
        },
        canvasType:{ //1通用； 2园区/企页
            type: Number,
            value: 1, 
        },
        page:{
            type: String,
            value: ''
        },
        qrBg:{
            type: String,
            value:''
        },
        canvasShow:{
            type: Boolean,
            value: false
        },
        canvasId:{
            type:String,
            value:''
        },
        shareType:{
            type: Number,
            value:1
        },
        //园区、企业首页分享
        title:{
            type: String,
            value: ''
        },
        desc:{
            type: String,
            value: ''
        },
    },

    /**
     * 组件的初始数据
     */
    data: {
        qrcode:'',
        userInfo: '',
    },

    /**
     * 组件实例进入页面节点树时执行
     */
    attached:function(){
        let that = this
        // console.log('组件实例进入页面节点树', app.globalData.userInfo)
        const userInfo = wx.getStorageSync('userInfo')
        wx.getImageInfo({
            src: userInfo.headimgUrl,
            success (res) {
                userInfo.localImg = res.path
                console.log('用户信息',userInfo.localImg)
                that.setData({
                    userInfo: userInfo
                })
            }
        })
    },

    /**
     * 监听数据变化
     */
    observers: {
        'canvasId': function(canvasId) {
        //   console.log('监听数据变化',canvasId)
          this.creat_wxmini_qrcode()
        }
    },

    /**
     * 组件的方法列表
     */
    methods: {
        /**
         * 获取我的二维码
         */
        creat_wxmini_qrcode:function(){
            let that = this
            wx.showLoading({
              title: '二维码生成中',
            })
            const userInfo = wx.getStorageSync('userInfo')
            let form = {
                userId: userInfo.id,
                page: that.data.page,
                type: that.data.type,   // 1.营销活动,2.园区首页id, 3企业首页id
            }
            form.type = that.data.type
            if( that.data.type == 2 ){//园区首页id
                form.gardenId = that.data.gardenId
            }else if( that.data.type == 3 ){//企业首页id
                form.enterpriseId = that.data.enterpriseId
            }
            ajax.post('/wx/appletQrCode/add', form).then( res => {
                if( res.code == 200 ){
                    var array = wx.base64ToArrayBuffer(res.msg)
                    wx.getFileSystemManager().writeFile({
                        filePath: wx.env.USER_DATA_PATH + "/qrminecode.png",
                        data: array,
                        success: (res) => {
                          that.setData({
                            qrcode: wx.env.USER_DATA_PATH + "/qrminecode.png" //绘制图片使用的图片路径
                          })
                        that.getShareImg()
                          // app.creat_records('share') //日志记录
                        }
                    })
                    console.log( '二维码', wx.env.USER_DATA_PATH + "/qrminecode.png" )
                    
                }
                wx.hideLoading()
            })
        },

        /**
         * canvas 画
         */
        getShareImg:function(){
            let that = this
            wx.showLoading({
              title: '生成中',
            })

            let imgbg = this.data.qrBg
            let qrcode = this.data.qrcode
            
            console.log( '获取图片',imgbg, qrcode )
           
            const canvas = wx.createCanvasContext(this.data.canvasId,this)

            //不同type画不同的图
            if( this.data.canvasType == 1 ){ //通用
                console.log('是否通用', this.data.canvasType)
                canvas.rect(0, 0,640,990)
                canvas.setFillStyle('white')
                canvas.fill()
                canvas.drawImage(imgbg, 0, 0, 750, 830 , 0, 0, 640, 830)
                canvas.drawImage(qrcode, 482, 840, 130, 130)
        
                //画个人头像 圆角
                console.log( that.data.userInfo.localImg )    
                canvas.save() // 绘制头像
                canvas.beginPath() // 开始创建一个路径
                canvas.arc(40 / 2 + 30, 40 / 2 + 850, 40 / 2, 0, Math.PI * 2, false)// 画一个圆形裁剪区域
                canvas.clip()// 裁剪
                canvas.drawImage(that.data.userInfo.localImg, 30, 850, 40, 40)
                // 恢复之前保存的绘图上下文
                canvas.restore()

                canvas.setFillStyle('#214081')
                canvas.font = 'normal bold 28px sans-serif'
                canvas.fillText(that.data.userInfo.nickName + '邀您查看', 90, 880)
                canvas.font = 'normal bold 24px sans-serif'
                canvas.fillText('扫码立即加入 ▶', 90, 930)
                canvas.drawImage(qrcode, 482, 840, 130, 130)
                canvas.draw()

            }else if( this.data.canvasType == 2  ){ //园区、企业
                // console.log('是否园区', that.data.canvasType,imgbg)
                wx.getImageInfo({
                    src: imgbg,
                    success (res) {
                        // console.log(res)
                        canvas.rect(0, 0,640,990)
                        canvas.setFillStyle('white')
                        canvas.fill()

                        canvas.drawImage(res.path, 0, 0, res.width, res.height , 0, 0, 640, 332)
                      
                        canvas.setFillStyle('#026064')
                        canvas.font = 'normal bold 36px sans-serif'
                        canvas.fillText('关于' + that.data.title,30,400)

                        let text = that.data.desc
                        canvas.setFillStyle('#333333')
                        canvas.font = 'normal 500 24px sans-serif'
                        let textStr = '' //临时存储切割字符串
                        let rows = [] //储存切割的字符串数组
                        let textArr = text.split('') //文字转数组
                        for( let i = 0; i < textArr.length; i++ ){
                            const metrics = canvas.measureText(textStr)
                            if( metrics.width < 560 ){
                                textStr += textArr[i]
                                if( i == textArr.length - 1 && metrics.width < 560 ){ //将最后一行切割文字插入数组
                                    rows.push(textStr)
                                }
                            }else{
                                i--
                                rows.push(textStr)
                                textStr = ''
                            }
                        }
                        rows.forEach( (ele, index) => {
                            if( index < 8 ){
                                canvas.fillText(ele, 30, 460 + index * 40)
                            }else if( index == 8 ){
                                canvas.fillText(ele + '...', 30, 460 + index * 40)
                            }
                        })

                        //画个人头像 圆角
                        // console.log( that.data.userInfo.localImg )    
                        canvas.save() // 绘制头像
                        canvas.beginPath() // 开始创建一个路径
                        canvas.arc(40 / 2 + 30, 40 / 2 + 850, 40 / 2, 0, Math.PI * 2, false)// 画一个圆形裁剪区域
                        canvas.clip()// 裁剪
                        canvas.drawImage(that.data.userInfo.localImg, 30, 850, 40, 40)
                        // 恢复之前保存的绘图上下文
                        canvas.restore()

                        canvas.setFillStyle('#214081')
                        canvas.font = 'normal bold 28px sans-serif'
                        canvas.fillText(that.data.userInfo.nickName + '邀您查看', 90, 880)
                        canvas.font = 'normal bold 24px sans-serif'
                        canvas.fillText('扫码立即加入 ▶', 90, 930)
                        canvas.drawImage(qrcode, 482, 840, 130, 130)

                        canvas.draw()

                    }
                })
            }

            
            wx.hideLoading()
        },

        /**
         * 保存分享图
         */
        saveShareImg:function(){
            let that = this
            wx.showLoading({
                title: '保存中',
            })
            console.log('canvasId2',that.data.canvasId)
            setTimeout( () => {
                wx.canvasToTempFilePath({
                    x: 0,
                    y: 0,
                    width: 640,
                    height: 990,
                    destWidth: 640 * 750 / wx.getSystemInfoSync().windowWidth, 
                    destHeight: 990 * 750 / wx.getSystemInfoSync().windowWidth,
                    quality:1,
                    canvasId: that.data.canvasId,
                    success(res) {
                        console.log(wx.getSystemInfoSync().pixelRatio,res.tempFilePath)
                        wx.saveImageToPhotosAlbum({
                            filePath:res.tempFilePath,
                            success(re) { 
                                wx.showToast({
                                title: '保存成功',
                                })
                            },
                            fail(){
                                wx.showToast({
                                title: '保存失败',
                                icon:'error'
                                })
                            },
                        })
                        wx.hideLoading()
                    },
                    complete(res){
                        console.log('保存图片',res,that.data.canvasId)
                    },
                },this)
            },1000)
        },
        

        /**
         * 打开分享图片弹窗
         */
        showShareImg:function(){
            let that = this
            wx.showLoading({
            title: '保存中',
            })
            setTimeout( () => {
                wx.canvasToTempFilePath({
                    x: 0,
                    y: 0,
                    width: 640,
                    height: 990,
                    destWidth: 640 * 750 / wx.getSystemInfoSync().windowWidth, 
                    destHeight: 990 * 750 / wx.getSystemInfoSync().windowWidth,
                    quality:1,
                    canvasId: that.data.canvasId,
                    success(res) {
                        console.log(wx.getSystemInfoSync().pixelRatio,res.tempFilePath)
                        wx.showShareImageMenu({
                            path: res.tempFilePath,
                        })
                        wx.hideLoading()
                    }
                },this)
            },1000)
        },

        /**
         * 隐藏画布
         */
        hiddenCanvas:function(){
            this.setData({
                canvasShow:false
            })
        },
    }
})
